<?php

namespace teach\service;

use backend\util\httpcurl\HttpCurl;
use Yii;

class User
{

    /**
     * 获取用户信息
     * @param $map
     * @param $param
     * @return array|false
     */
    public function userInfo($map, $param)
    {
        $info = $this->userMsg($map);
        $count = $this->userOrderCount($param);
        $info['order_count'] = $count;
        return $info;
    }

    /**
     * 获取用户信息
     * @param $condition
     * @return array|false
     */
    public function userMsg($condition)
    {
        $sql = "SELECT id, openid, nickname, avatar_url, mall_rname, mall_total_fee, mall_id,mall_is, phone, score, score_total,recharge, roles FROM edu_user WHERE " . $condition;
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    /**
     * 统计订单数
     * @param $condition
     * @return false|null|string
     */
    public function userOrderCount($condition)
    {
        $sql = "SELECT COUNT(*) FROM mall_order WHERE " . $condition;
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    /**
     * 统计今天订单数
     * @param $condition
     * @return false|int|null|string
     */
    public function userTodayOrderCount($condition)
    {
        $todayStar = strtotime(date("Y-m-d 00:00:00"), time());
        $todayEnd = $todayStar + 24 * 3600;
        $sql = "SELECT COUNT(*) FROM mall_order WHERE $condition  AND create_time > {$todayStar} AND create_time < {$todayEnd}";
        return Yii::$app->db->createCommand($sql)->queryScalar();

    }

    /**
     * 今天营业额
     * @param $condition
     * @return false|int|null|string
     */
    public function userTodayOrderTurnover($condition)
    {
        $todayStar = strtotime(date("Y-m-d 00:00:00"), time());
        $todayEnd = $todayStar + 24 * 3600;
        $sql = "SELECT SUM(total_fee) FROM mall_order WHERE  {$condition}  AND create_time > {$todayStar} AND create_time < {$todayEnd}";
        $res = Yii::$app->db->createCommand($sql)->queryScalar();
        return $res ? $res : 0;
    }

    /**
     * 今天营业额
     * @param $condition
     * @return false|int|null|string
     */
    public function userOrderTurnover($condition)
    {
        $sql = "SELECT SUM(total_fee) FROM mall_order WHERE " . $condition;
        $res = Yii::$app->db->createCommand($sql)->queryScalar();
        return $res ? $res : 0;
    }


    /**
     * 填写真实姓名
     * @param $map
     * @param $param
     * @return int
     */
    public function userRealName($map, $param)
    {
        $sql = "UPDATE edu_user SET {$param} WHERE " . $map;
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 获取金额
     * @param $condition
     * @return array|false
     */
    public function userSum($condition)
    {
        $sql = "SELECT id, mall_total_fee, recharge FROM edu_user WHERE " . $condition;
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    /**
     * 今天收益
     * @param $condition
     * @return false|null|string
     */
    public function userTodayProfit($condition)
    {
        $todayStar = strtotime(date("Y-m-d 00:00:00"), time());
        $todayEnd = $todayStar + 24 * 3600;
        $sql = "SELECT SUM(amount) FROM mall_bill WHERE " . $condition . " AND create_time > {$todayStar} AND create_time < {$todayEnd}";
        $res = Yii::$app->db->createCommand($sql)->queryScalar();
        return $res ? $res : 0;
    }

    /**
     * 全部收益
     * @param $condition
     * @return false|null|string
     */
    public function userProfit($condition)
    {
        $sql = "SELECT SUM(amount) FROM mall_bill WHERE " . $condition;
        $res = Yii::$app->db->createCommand($sql)->queryScalar();
        return $res ? $res : 0;
    }


    /**
     *统计用户未分配金额 即待算金额
     * @param $condition
     * @return false|null|string
     */
    public function userStayCount($condition)
    {
       $sql = "SELECT SUM(amount) FROM mall_bill WHERE {$condition} ";
       $res = Yii::$app->db->createCommand($sql)->queryScalar();
       return $res ? $res : 0;
    }


    /**
     * 提现事务
     * @param $map
     * @return bool
     */
    public function userAppear($map)
    {

        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            $db->createCommand()->insert('mall_appear', $map)->execute();
            //同时将金额放入到冻结中
            $sql = "UPDATE edu_user SET mall_total_fee = mall_total_fee - {$map['amount']}, mall_put_money = mall_put_money + {$map['amount']} WHERE id = {$map['uid']}";
            $db->createCommand($sql)->execute();

            $transaction->commit();
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
//            throw $e;
            return false;
        }

    }

    /**
     * 收益列表
     * @param $condition
     * @param $page
     * @param int $pre_page
     * @return array
     */
    public function userIncomeDetail($condition, $page, $pre_page = 10)
    {
        $count = $this->incomeCount($condition);
        $data = ['total' => 0, 'total_page' => 0, 'page' => 1, 'pre_page' => $pre_page, 'lists' => []];

        if ($count) {
            $total_page = ceil($count / $pre_page);

            $sql = "SELECT uid, sid, mid, direct, out_trade_no, amount, create_time FROM mall_bill WHERE " . $condition . " ORDER BY create_time DESC " . " LIMIT " . ($page - 1) * $pre_page . " , " . $pre_page;
            $res = Yii::$app->db->createCommand($sql)->queryAll();

            $data = ['total' => $count, 'total_page' => $total_page, 'page' => $page, 'pre_page' => $pre_page, 'lists' => $res];
        }

        return $data;
    }

    /**
     * 统计收益的条数
     * @param $condition
     * @return false|null|string
     */
    public function incomeCount($condition)
    {
        $sql = "SELECT COUNT(*) FROM mall_bill WHERE " . $condition;
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    /**
     * 提现记录
     * @param $condition
     * @param $page
     * @param $pre_page
     * @return array
     */
    public function userCashRecord($condition, $page, $pre_page = 10)
    {
        $count = $this->cashCount($condition);
        $data = ['total' => 0, 'total_page' => 0, 'page' => 1, 'pre_page' => $pre_page, 'lists' => []];

        if ($count) {
            $total_page = ceil($count / $pre_page);

            $sql = "SELECT * FROM mall_appear WHERE " . $condition . " ORDER BY create_time DESC " . " LIMIT " . ($page - 1) * $pre_page . " , " . $pre_page;
            $res = Yii::$app->db->createCommand($sql)->queryAll();

            $data = ['total' => $count, 'total_page' => $total_page, 'page' => $page, 'pre_page' => $pre_page, 'lists' => $res];
        }

        return $data;
    }

    /**
     * 统计提现记录
     * @param $condition
     * @return false|null|string
     */
    public function cashCount($condition)
    {
        $sql = "SELECT COUNT(*) FROM mall_appear WHERE " . $condition;
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }


    /**
     * 待发货
     * @param $condition
     * @return false|null|string
     */
    public function orderStatus($condition)
    {
        $sql = "SELECT COUNT(*) FROM mall_order WHERE {$condition}";
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    /**
     * 查找订单列表
     * @param $map
     * @param $page
     * @param int $pre_page
     * @return array
     */
    public function orderList($map, $page, $pre_page = 10)
    {
        $count = $this->orderCount($map);
        $data = ['total' => 0, 'total_page' => 0, 'page' => 1, 'pre_page' => $pre_page, 'lists' => []];

        if ($count) {
            $total_page = ceil($count / $pre_page);
            $sql = "SELECT * FROM mall_order WHERE {$map} ORDER BY create_time DESC LIMIT " . ($page - 1) * $pre_page . " , " . $pre_page;
            $res = Yii::$app->db->createCommand($sql)->queryAll();

            $resData = [];
            foreach ($res as $_key => $_val) {
//                $sqlSku = "SELECT * FROM mall_order_list WHERE out_trade_no = {$_val['out_trade_no']}";
                $sqlSku = "SELECT o.count, p.id, o.price, o.value ,p.img, p.title FROM mall_order_list AS o LEFT JOIN mall_product AS p ON o.pid = p.id WHERE o.out_trade_no = '{$_val['out_trade_no']}'";
                $sku = Yii::$app->db->createCommand($sqlSku)->queryAll();

                $sqlUser = "SELECT id, nickname, mall_rname FROM edu_user WHERE id = {$_val['uid']}";
                $user = Yii::$app->db->createCommand($sqlUser)->queryOne();

                $_val['real_name'] = $user['mall_rname'];
                $_val['nickname'] = $user['nickname'];

                $_val['list'] = $sku;
                $resData[$_key] = $_val;
            }

            $data = ['total' => $count, 'total_page' => $total_page, 'page' => $page, 'pre_page' => $pre_page, 'lists' => $resData];
        }
        return $data;
    }

    /**
     * 统计订单数
     * @param $map
     * @return false|null|string
     */
    public function orderCount($map)
    {
        $sql = "SELECT COUNT(*) FROM mall_order WHERE {$map}";
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    /**
     * 修改订单状态
     * @param $map
     * @param $param
     * @return int
     */
    public function orderChange($map, $param)
    {
        $sql = "UPDATE mall_order SET {$map} WHERE {$param}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 查找物流
     * @param $logistic
     * @return bool|string
     */
    public function checkLogistic($logistic)
    {
        $key = 'QTREuniG4402';
        $code_url = 'http://www.kuaidi100.com/autonumber/auto?num=' . $logistic . '&key=' . $key;
        $logistics = HttpCurl::http_get($code_url);
        if ($logistics == '[]') {
            return false;
        }
        $code = json_decode($logistics, true)[0]['comCode'];
        $post_data = array();
        $post_data["customer"] = '67F6EC4DAAC06F2614EF1392ED6F9641';
        $post_data["param"] = '{"com":"' . $code . '","num":"' . $logistic . '"}';
        $url = 'http://poll.kuaidi100.com/poll/query.do';
        $post_data["sign"] = md5($post_data["param"] . $key . $post_data["customer"]);
        $post_data["sign"] = strtoupper($post_data["sign"]);
        $o = "";
        foreach ($post_data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";        //默认UTF-8编码格式
        }
        $post_data = substr($o, 0, -1);
        $result = HttpCurl::http_post($url, $post_data);
        return $result;
    }

    /**
     * @param $map
     * @param $where
     * @return int
     */
    public function orderLogistic($map, $where)
    {
        $sql = "UPDATE mall_order SET {$map} WHERE {$where}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 查找其中一条订单记录
     * @param $map
     * @return array|false
     */
    public function orderOne($map)
    {
        $sql = "SELECT * FROM mall_order WHERE {$map}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    /**
     * 提现说明
     * @param $where
     * @return array|false
     */
    public function presentExplain($where)
    {
        $sql = "SELECT title, `desc` FROM mall_ad_share WHERE {$where}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    /**
     * 查找信息列表
     * @param $where
     * @param $page
     * @param int $pre_page
     * @return array
     */
    public function userNotice($where, $page, $pre_page = 10)
    {
        $count = $this->noticeCount($where);
        $data = ['total' => 0, 'total_page' => 0, 'page' => 1, 'pre_page' => $pre_page, 'lists' => []];

        if ($count) {
            $total_page = ceil($count / $pre_page);
            $offset = ($page - 1) * $pre_page;
            $sql = " SELECT * FROM mall_notice WHERE {$where} ORDER BY create_time DESC LIMIT {$offset} , {$pre_page}";
            $res = Yii::$app->db->createCommand($sql)->queryAll();
            $data = ['total' => $count, 'total_page' => $total_page, 'page' => $page, 'pre_page' => $pre_page, 'lists' => $res];
        }
        return $data;

    }

    /**
     * 统计信息条数
     * @param $where
     * @return false|null|string
     */
    public function noticeCount($where)
    {
        $sql = "SELECT COUNT(*) FROM mall_notice WHERE {$where}";
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    /**
     * @param $where
     * @return int
     */
    public function noticeRead($where)
    {
        $sql= "UPDATE mall_notice SET status = 2 WHERE {$where}";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 根据订单号获取订单列表
     * @param $out_trade_no
     * @return array
     */
    public function orderListAll($out_trade_no)
    {
        $sql = "SELECT * FROM mall_order_list WHERE out_trade_no = '{$out_trade_no}'";
        return Yii::$app->db->createCommand($sql)->queryAll();
    }

    /**
     * 货物售卖量增加
     * @param $map
     * @param $where
     * @return int
     */
    public function productSaleAdd($map, $where)
    {
        $sql  = "UPDATE mall_product SET {$map} WHERE {$where} ";
        return Yii::$app->db->createCommand($sql)->execute();
    }

    /**
     * 根据id获取用户
     * @param $where
     * @return array
     */
    public function storeOne($where)
    {
        $sql = "SELECT openid, id FROM edu_user WHERE  {$where}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    /**
     * 查找rule
     * @param $mall_id
     * @return array|false
     */
    public function distribution($mall_id)
    {
        $sql = "SELECT * FROM mall_distribution WHERE mid = {$mall_id}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }

    /**
     * 获取用户的积分记录
     * @param $map
     * @param $page
     * @param int $pre_page
     * @return array
     */
    public function userScoreRecord($map, $page, $pre_page = 10)
    {
        $count = $this->scoreCount($map);
        $data = ['total' => 0, 'total_page' => 0, 'page' => 1, 'pre_page' => $pre_page, 'lists' => []];
        if ($count) {
            $total_page = ceil( $count / $pre_page);
            $offset = ($page - 1) * $pre_page;
            $sql = " SELECT id, uid, mid, score, des, create_time FROM mall_score_record WHERE {$map} ORDER BY create_time DESC LIMIT {$offset}, $pre_page";
            $res = Yii::$app->db->createCommand($sql)->queryAll();
            $data = ['total' => $count, 'total_page' => $total_page, 'page' => $page, 'pre_page' => $pre_page, 'lists' => $res];
        }
        return $data;

    }

    /**
     * 统计积分记录
     * @param $map
     * @return false|null|string
     */
    private function scoreCount($map)
    {
        $sql = " SELECT COUNT(*) FROM mall_score_record WHERE {$map} ";
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    /**
     * 拿取充值记录
     * @param $map
     * @param $page
     * @param $pre_page
     * @return array
     */
    public function userRechargeRecord($map, $page, $pre_page)
    {
        $count = $this->rechargeCount($map);
        $data = ['total' => 0, 'total_page' => 0, 'page' => 1, 'pre_page' => $pre_page, 'lists' => []];
        if ($count) {
            $total_page = ceil( $count / $pre_page);
            $offset = ($page - 1) * $pre_page;
            $sql = "SELECT id, uid, mid, recharge, out_trade_no, create_time, recharge AS score FROM mall_recharge_record WHERE {$map} ORDER BY create_time DESC LIMIT {$offset}, $pre_page";
            $res = Yii::$app->db->createCommand($sql)->queryAll();
            $data = ['total' => $count, 'total_page' => $total_page, 'page' => $page, 'pre_page' => $pre_page, 'lists' => $res];
        }
        return $data;
    }

    /**
     * 支票充值记录
     * @param $map
     * @return false|null|string
     */
    private function rechargeCount($map)
    {
        $sql = "SELECT COUNT(*) FROM mall_recharge_record WHERE {$map}";
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    /**
     * 申请退款事务
     * @param $map
     * @param $oid
     * @param $out_trade_no
     * @return bool
     */
    public function userRefund($map, $oid, $out_trade_no)
    {
        $db = Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            //更新订单表为退款状态
            $sqlTotal = "UPDATE mall_order SET status = -2 WHERE id = {$oid}";
            $db->createCommand($sqlTotal)->execute();

            //更新支付表表为退款状态
            $sqlTotalPay = "UPDATE mall_pay SET status = -1 WHERE out_trade_no = '{$out_trade_no}'";
            $db->createCommand($sqlTotalPay)->execute();
            //插入退款记录
            $db->createCommand()->insert('mall_product_refund_reason', $map)->execute();
            $transaction->commit();
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            return false;
        }
    }

}